package org.rency.common.redis;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.RedisNode.RedisNodeBuilder;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.util.Assert;

/**
 * Redis集群配置工厂
 * @author: user_rcy@163.com
 * </br>Created on 2016年4月21日
 * @version: V1.0.0
 * @since JDK 1.8
 */
public class ClusterRedisSentinelConfiguration extends RedisSentinelConfiguration implements InitializingBean{
	
	private List<RedisNodeDomain> nodeList = Collections.synchronizedList(new ArrayList<RedisNodeDomain>());
	
	private String masterName;
	
	private String serverHosts;
	
	@Override
	public void afterPropertiesSet() throws Exception {
		this.validator();
		RedisNodeBuilder masterNodeBuilder = new RedisNodeBuilder();
		RedisNode masterNode = masterNodeBuilder.withName(this.masterName).build();
		setMaster(masterNode);
		Set<RedisNode> sentinels = new HashSet<RedisNode>();
		for(RedisNodeDomain node : this.nodeList){
			RedisNode redisNode = new RedisNode(node.getNodeAddr(),node.getNodePort());
			sentinels.add(redisNode);
		}
		setSentinels(sentinels);
	}
	
	private void validator(){
		Assert.notNull(this.masterName, "Cluster Redis Master Name Is Empty!");
		Assert.notNull(this.serverHosts, "Cluster Redis Server Hosts Is Empty!");
		String[] nodes = this.serverHosts.split(",");
		for(String node : nodes){
			String[] arr = node.split(":");
			Assert.isTrue((node.split(":").length == 2), "Cluster Redis Server Hosts Format Invalid, For Example : '127.0.0.1:6379,127.0.0.2:6379' etc.");
			RedisNodeDomain redisNode = new RedisNodeDomain(arr[0],Integer.parseInt(arr[1]),0);
			nodeList.add(redisNode);
		}
		Assert.isTrue(CollectionUtils.isNotEmpty(nodeList), "Cluster Redis Server Hosts Is Empty!");
	}

	public String getMasterName() {
		return masterName;
	}

	public void setMasterName(String masterName) {
		this.masterName = masterName;
	}

	public String getServerHosts() {
		return serverHosts;
	}

	public void setServerHosts(String serverHosts) {
		this.serverHosts = serverHosts;
	}

}